﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MagicText.Utils
{
    public delegate string ProcessLineEventHandler(object sender, string line);

    public class TextParser
    {
        private string sourceText;
        private event ProcessLineEventHandler processLine;

        public event ProcessLineEventHandler ProcessLine
        {
            add
            {
                this.processLine += value;
            }
            remove
            {
                this.processLine -= value;
            }
        }

        public TextParser(string sourceText)
        {
            this.sourceText = sourceText;
        }

        public string Read()
        {
            if (processLine != null)
            {
                StringBuilder result = new StringBuilder();
                using (StringReader reader = new StringReader(sourceText))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        result.AppendLine(processLine.Invoke(this, line));
                    }
                }

                return result.ToString();
            }
            return string.Empty;
        }

        public string ReadWithoutEmptyLines()
        {
            if (processLine != null)
            {
                StringBuilder result = new StringBuilder();
                using (StringReader reader = new StringReader(sourceText))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string newLine = processLine.Invoke(this, line);
                        if (!string.IsNullOrEmpty(newLine))
                        {
                            result.AppendLine(newLine);
                        }
                    }
                }

                return result.ToString();
            }
            else
            {
                StringBuilder result = new StringBuilder();
                using (StringReader reader = new StringReader(sourceText))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (!string.IsNullOrEmpty(line))
                        {
                            result.AppendLine(line);
                        }
                    }
                }

                return result.ToString();
            }

            // processeventhandler p = delegate (object sender, strin line)
            // {
            //    methode
            //}
            //start parse(p);
        }

    }
}
